<template>
  <div class="character">
    <div class="main">
      <div class="allsearch">
        <section class="search-content">
          <el-row style="width:100%;">
            <el-col :span="14">
              <el-input
                v-model="listQuery.name"
                style="width:40%;"
                placeholder="关键词"
                @keyup.enter.native="handleFilter"
              />
              <el-button type="primary" size="medium" @click="handleFilter">搜索</el-button>
              <el-button size="medium" type="info" @click="clearParams">清空</el-button>
            </el-col>
            <el-col :span="10">
              <div style="float:right;">
                <el-button type="primary" size="medium" @click="DialogVisible= true">新增角色</el-button>
                <el-button type="primary" size="medium" @click="initRoleData()">初始化默认角色</el-button>
              </div>
            </el-col>
          </el-row>
        </section>
      </div>
      <el-dialog :visible.sync="DialogVisible" :before-close="cancelAddDialog" title="新增角色" width="38%">
        <el-form :model="Role" label-position="right" label-width="80px" ref="dataForm">
          <div style="width:50%;float:left;">
            <el-tree :data="data" :props="defaultProps" show-checkbox @check-change="handleNodeClick" ref="tree"/>
          </div>
          <div style="width:50%;float:left;border-left:1px solid #e6eaee;height:500px;">
            <el-form-item label="名称">
              <el-input v-model="Role.name" style="width:80%"/>
              <el-input v-model="Role.authorityIds" type="hidden"/>
            </el-form-item>
            <el-form-item label="编码">
              <el-input v-model="Role.roleCode" style="width:80%"/>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelAddDialog">取 消</el-button>
          <el-button type="primary" @click="createData()">添 加</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="handleEdit" :before-close="cancelUpdateDialog" title="编辑角色" width="38%">
        <el-form :model="Role" label-position="right" label-width="80px" ref="updateForm">
          <div style="width:50%;float:left;">
            <el-tree :data="data" :props="defaultProps" node-key="id" :default-checked-keys="Role.checkedNodes" show-checkbox @check-change="handleNodeClick" ref="updatetree"/>
          </div>
          <div style="width:50%;float:left;border-left:1px solid #e6eaee;height:500px;">

            <el-form-item label="名称">
              <el-input v-model="Role.name" style="width:80%"/>
              <el-input v-model="Role.authorityIds" type="hidden"/>
            </el-form-item>
            <el-form-item label="编码">
              <el-input v-model="Role.roleCode" style="width:80%"/>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelUpdateDialog">取 消</el-button>
          <el-button type="primary" @click="updateData()">保 存</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="handleShow" :before-close="cancelShowDialog" title="查看角色" width="38%">
        <el-form :model="Role" label-position="right" label-width="80px" ref="showForm">
          <div style="width:50%;float:left;">
            <el-tree :data="data" :props="defaultProps" node-key="id" :default-checked-keys="Role.checkedNodes" show-checkbox ref="showtree"/>
          </div>
          <div style="width:50%;float:left;border-left:1px solid #e6eaee;height:500px;">
            <el-form-item label="名称">
              <el-input v-model="Role.name" style="width:80%"/>
              <el-input v-model="Role.authorityIds" type="hidden"/>
            </el-form-item>
            <el-form-item label="编码">
              <el-input v-model="Role.roleCode" style="width:80%"/>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelShowDialog">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 删除 -->
      <el-dialog :visible.sync="handleDelete" width="25%">
        <div style="width:100%;float:left;height:42px;">确定要删除吗?</div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="deleteData(deleteRow)">确定</el-button>
          <el-button @click="handleDelete = false">取消</el-button>
        </div>
      </el-dialog>
      <!-- 删除 -->
      <el-table
        :table-label="tableLabel"
        :table-data="listFilter.slice((currentpage-1)*pagesize,currentpage*pagesize)"
        :list-loading="listLoading"
      >
        <el-table-column slot="button" :min-width="2" label="操作" prop="manage" align="center">
          <template slot-scope="scope">
            <el-button @click="showCLick(scope.row)">查看</el-button>
            <el-button @click="updateCLick(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.type==='0'" @click="deleteCLick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        :current-page="currentpage"
        :page-size="pagesize"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
  import ElTable from '@/components/Eltable'
  import { scrollTo } from '@/utils/scrollTo' // 上下滑动组件
  import Pagination from '@/components/Pagination' // 分页组件
  import { add, deleteRole, getRoutes, initRoleData, list, updateRole } from '@/api/system/role' // 数据接口
  import { getTenantId, getUserName } from '@/utils/auth'

  export default {
    components: {
      ElTable,
      Pagination
    },
    data() {
      return {
        Role: {
          name: '',
          tenantId: '',
          creator: '',
          roleCode: '',
          authorityIds: '',
          checkedNodes: []
        },
        Authority: {
          id: '',
          authorityCode: ''
        },
        data: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        formLabelWidth: '135px',
        DialogVisible: false,//新增
        handleEdit: false,//编辑
        handleShow: false,//查看
        handleDelete: false,//删除
        deleteRow: '',
        deleteCLick(row) {
          this.handleDelete = true
          this.deleteRow = row
        },
        // 列表编辑按钮
        updateCLick(row) {
          this.handleEdit = true
          this.Role = Object.assign({}, row)
          if (this.Role.checkedNodes) {
            this.$nextTick(() => {
              this.$refs.updatetree.setCheckedKeys(this.Role.checkedNodes)
            })
          } else {
            this.$nextTick(() => {
              this.$refs.updatetree.setCheckedKeys([])
            })
          }
        },
        // 查看
        showCLick(row) {
          this.handleShow = true
          this.Role = Object.assign({}, row)
          if (this.Role.checkedNodes) {
            this.$nextTick(() => {
              this.$refs.showtree.setCheckedKeys(this.Role.checkedNodes)
            })
          } else {
            this.$nextTick(() => {
              this.$refs.showtree.setCheckedKeys([])
            })
          }
        },
        total: 0,
        currentpage: 1,
        pagesize: 10,
        tableLabel: [
          {
            label: '角色名称', width: '3', prop: 'name'
          }, {
            label: '编码', width: '2', prop: 'roleCode', isOpera: true
          }, {
            label: '创建时间', width: '2', prop: 'createTimeTimeStr', isOpera: true
          }, {
            label: '创建者', width: '1', prop: 'creator'
          }
        ],
        tableData: [],
        listFilter: [],
        listLoading: false,
        listQuery: {
          name: '' // 角色名称
        }
      }
    },
    mounted() {
      this.getData()
      this.getRouteData()
    },
    methods: {
      //接口获取数据
      getData() {
        this.listLoading = true
        list(getTenantId()).then(response => {
          this.tableData = response.data.items
          this.total = response.data.items.length
          this.listFilter = response.data.items
          this.listLoading = false
        })
      },
      getRouteData() {
        getRoutes().then(response => {
          this.data = response.data.items
        })
      },
      handleNodeClick() {
        this.$refs.updatetree.getCheckedNodes().map(i => {
          this.Role.checkedNodes.push(i.id)
        })
      },
      // 检索列表,return所需数据
      handleFilter() {
        this.listFilter = this.tableData.filter(item => {
          if (!this.listQuery.name) return true
          return !(this.listQuery.name && item.name.toLowerCase().indexOf(this.listQuery.name.toLowerCase()) < 0)
        })
        this.total = this.listFilter.length
      },
      clearParams() {
        this.listQuery.name = ''
        this.getData()
      },
      handleClick() {
      },
      handleSizeChange(val) {
        this.currentpage = 1
        this.pagesize = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.Role.tenantId = getTenantId()
            this.Role.creator = getUserName()
            add(this.Role).then(() => {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              setTimeout(function() {
              }, 150)
              this.getData()
              this.$refs['dataForm'].resetFields()
              this.DialogVisible = false
            })
          }
        })
      },
      initRoleData() {
        initRoleData(getTenantId()).then(() => {
          this.$notify({
            title: '成功',
            message: '角色初始化成功',
            type: 'success',
            duration: 2000
          })
          setTimeout(function() {
          }, 150)
          this.getData()
        })
      },
      updateData() {
        this.handleEdit = false
        this.$refs['updateForm'].validate((valid) => {
          if (valid) {
            updateRole(this.Role).then(() => {
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getData()
              this.$refs['updateForm'].resetFields()
            })
          }
        })
      },
      cancelShowDialog() {
        this.handleShow = false
        this.$refs['showForm'].resetFields()
        this.Role = {
          name: '',
          tenantId: '',
          creator: '',
          roleCode: '',
          authorityIds: '',
          checkedNodes: []
        }
      },
      cancelUpdateDialog() {
        this.handleEdit = false
        this.$refs['updateForm'].resetFields()
        this.Role = {
          name: '',
          tenantId: '',
          creator: '',
          roleCode: '',
          authorityIds: '',
          checkedNodes: []
        }
      },
      cancelAddDialog() {
        this.DialogVisible = false
        this.$refs['dataForm'].resetFields()
        this.Role = {
          name: '',
          tenantId: '',
          creator: '',
          roleCode: '',
          authorityIds: '',
          checkedNodes: []
        }
      },
      deleteData(row) {
        this.handleDelete = false
        deleteRole(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getData()
        })
      }
    }
  }
</script>

<style lang="scss">
  .character {
    .main {
      padding: 0 20px;
    }

    .allsearch {
      margin-top: 14px;
      padding: 0;

      .search-content {
        width: 100%;
      }
    }

    .el-dialog {
      border-radius: 5px;
      overflow: hidden;
    }
  }
</style>
